/****************************************************
          File Name:35-1.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Mon 01 Sep 2014 03:56:11 PM CST
*****************************************************/
// fake nice command
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/time.h>
#include<sys/resource.h>
int err(int eRR, char *fun)
{
    if(eRR==-1)
    {
        perror(fun);
        exit(errno);
    }
    else
        return 0;
}

int main(int argc,char *argv[])
{
    int res;
    id_t who;
    int prio;
    if(argc<2)
        exit(1);
    if(strcmp(argv[1],"-get")==0)
    {
        who=atoi(argv[3]);
        switch(argv[2][0])
        {
            case 'p':
                res=getpriority(PRIO_PROCESS,who);
                err(res,"getpriority");
                printf("nice: %d\n",res);
                break; 
            case 'g':
                res=getpriority(PRIO_PGRP,who);
                err(res,"getpriority");
                printf("nice: %d\n",res);
                break;
            case 'u':
                res=getpriority(PRIO_USER,who);
                err(res,"getpriority");
                printf("nice: %d\n",res);
            break;
        }
    } 
    else if(strcmp(argv[1],"-set")==0)
    {
        who=atoi(argv[3]);
        prio=atoi(argv[4]);
        switch(argv[2][0])
        {
            case 'p':
                res=setpriority(PRIO_PROCESS,who,prio);
                err(res,"setpriority");
                break;
            case 'g':
                res=setpriority(PRIO_PGRP,who,prio);
                err(res,"setpriority");
                break;
            case 'u':
                res=setpriority(PRIO_USER,who,prio);
                err(res,"setpriority");
                break;
        }
    }
    else
    {
        printf("%s -[res=get|res=set] [p|g|u] pid (number[when with '-set'])\n",argv[0]);
        exit(1);
    }

    exit(0);
}
